<template>
	<div :class="$style.buyin">
		<div
			:class="!!gameId ? $style['game-panel'] : $style.panel">
			<!-- 股票代码输入框 -->

			<img v-if="gameId" src="~assets/images/trade/monibisai.png" :class="$style.trade_mark_bg" alt="">
			<img v-else="gameId" src="~assets/images/trade/monijiaoyi.png" :class="$style.trade_mark_bg" alt="">

			<stock-code-input
				v-on:setfifth="setFifth"
				v-on:startroll="startRoll"/>

			<!-- 限价委托输入框 -->
			<delegate-input :gameid="gameId" :class="$style.bg_position"/>

			<!-- 买入数量框 -->
			<buy-amount :gameid="gameId" :class="$style.bg_position"/>

			<!-- 快捷选择 -->
			<warehouse-picker :gameid="gameId"  :class="$style.bg_position"/>
			<div :class="$style.max">
				最大可买
				<span :class="$style.maxnum">
					{{ buyEnableVol || '-' }} 股
				</span>
			</div>
		</div>

		<group-picker v-if="!gameId"/>

		<fifth-position
			v-on:setprice="setPrice"></fifth-position>

		<div :class="$style.buttons">
			<div :class="$style.real" @click="toReal">转入实盘</div>
			<div :class="$style.buy" @click="commitBuy">
				<i class="iconfont m-r-xs">&#xe630;</i>
				模拟买入
			</div>
		</div>

		<trade-to-real-modal />
	</div>
</template>

<script>
	import StockCodeInput from './StockCodeInput'
	import WarehousePicker from './WarehousePicker'
	import RemoteDAO from '../../../common/remoteDAO'
	import LocalDAO from '../../../common/localDAO'
	import GroupPicker from './GroupPicker'
	import DelegateInput from './DelegateInput'
	import BuyAmount from './BuyAmount'
	import FifthPosition from './FifthPosition'
	import TradeToRealModal from 'components/modal/TradeToRealModal'
	const queryString = require('query-string')
	var gid
	/**
	 * 模拟交易买入页面根组件
	 * @param {String} stockCode 买入股票代码
	 * @param {String} stockName 买入股票名称
	 * @param {String} marketCd 买入股票所在市场
	 * @example this.$router.push({path: '/trade/buy-in', query: {stockCode: '123456', stockName: 'xxx', marketCd: '1'} })
	 */
	export default {
		components: {
			StockCodeInput,
			WarehousePicker,
			GroupPicker,
			FifthPosition,
			DelegateInput,
			BuyAmount,
			TradeToRealModal
		},

		data () {
			const { gameId = '' } = this.$route.query
			return {
				gameId,
				prices: {}
			}
		},

		mounted () {
			$(document).unbind().bind('click', () => {
				this.$store.dispatch('setBuySearchResultsVisible', false) // hide stock comp
			})

			const { stockCode = '', marketCd = '', stockName = '' } = this.$route.query
			if (!stockCode || stockCode.length !== 6) return

			this.$store.dispatch('setBuyDelegatePrice', '')
			RemoteDAO.callNativeSearchStock(stockCode, results => {
				if (results.error == '0') {
					const _stock = results.data[0]
					this.reloadFivePrices(_stock)
					// set some data in store
					this.$store.dispatch('setBuyStockCode', _stock.stockCode.slice(2))
					this.$store.dispatch('setBuyStockMarket', _stock.stockCode.slice(0, 2))
	   			this.$store.dispatch('setBuyStockName', _stock.stockName)
				} else {
					this.$store.dispatch('setTip', { text: results.data })
				}
			})
		},
		created() {
			this.gameId = this.$route.query.gameId || gid
		},
		beforeRouteEnter (to, from, next) {
			const { gameId = '', cleanStorage } = from.query
			const extraQuery = cleanStorage !== undefined && from.path.includes('trade')
				? { cleanStorage } : {}
			gid = gameId
			if (!!gameId) {
				next(vm => {
					vm.$router.replace({ path: to.path, query: Object.assign({}, to.query, { gameId }, extraQuery) })
				})
			} else {
				next(vm => {
					vm.$router.replace({ path: to.path, query: Object.assign({}, 
						to.query, extraQuery) })
				})
			}
		},
		beforeRouteUpdate (to, from, next) {
			const { gameId = '', cleanStorage } = to.query
			if (!!gameId) {
				this.gameId = gameId
				this.$route.query.gameId = gameId
			}
			if (cleanStorage !== undefined) {
				this.$route.query.cleanStorage = cleanStorage
			}
		},

		computed: {
			buyStockGroups () {
				return [this.$store.state.buyStockGroups]
			},

			buyEnableVol () {
				return parseInt(this.$store.state.buyEnableVol) || 0
			},

			buyStockCode () {
				return this.$store.state.buyStockCode
			},

			buyAmount () {
				return this.$store.state.buyAmount
			},

			delegatePrice () {
				return parseFloat(this.$store.state.buyDelegatePrice).toFixed(2)
			},
			panelStyle () {
				return {
					// backgroundColor: !!this.gameId ? '#902AFF' : '#EC4F4F'
				}
			}
		},

		beforeDestroy () {
			if (this._interval)
				clearInterval(this._interval)
		},

		methods: {

			setFifth (fifthData) {
				this.$store.dispatch('setBuyFivePrices', fifthData)
				this.$store.dispatch('setBuyDelegatePrice', fifthData.buyPrice1)
			},

			startRoll (stockCode) {
				if (this._interval) {
					clearInterval(this._interval)
				}

				this._interval = setInterval(() => {
					RemoteDAO.callNativeFivePrice(stockCode,  results => {
						this.$store.dispatch('setBuyFivePrices', results.data)
					})
				}, 5000)
			},

			setPrice (price) {
				this.$store.dispatch('setBuyDelegatePrice', price)
			},

			toReal () {
        let kv = {"usercode": LocalDAO.getUserCode()}
        TDAPP.onEvent("4001","",kv)
        TDAPP.send()
				const market = this.$store.state.buyStockMarket
				const marketCd = market === 'SH' ? '1' : '0'
				this.$store.dispatch('setModal', { visible: true, modalId: 'tradeToRealModal', stockCode: this.buyStockCode, marketCd:marketCd, tradeType: 'buy' })
			},

			reloadFivePrices (stock) {
				setTimeout(() => {
					RemoteDAO.callNativeFivePrice(stock.stockCode, results => {
						this.setFifth(results.data)
					})
				}, 100)

				if (this._interval) {
					clearInterval(this._interval)
				}

				this._interval = setInterval(() => {
					RemoteDAO.callNativeFivePrice(stock.stockCode, results => {
						this.$store.dispatch('setBuyFivePrices', results.data)
						// this.setFifth(results.data)
					})
				}, 5000)
			},

			showErr (msg) {
				this.$store.dispatch('setTip', { text: msg })
			},

			commitBuy () {
        let kv = {"usercode": LocalDAO.getUserCode()}
        TDAPP.onEvent("20004","",kv)
        TDAPP.send()
				const groupId = this.$store.state.buyGroupId === 'default' ? '' : this.$store.state.buyGroupId
				const marketCd = this.$store.state.buyStockMarket === 'SH' ? '1' : '0'
				const { gameId } = this.$route.query

				// validate
				if (this.buyStockCode.length !== 6 || !parseInt(this.buyStockCode)) {
					this.showErr('请输入正确的股票代码!')
					return
				}

				if ((this.$store.state.buyDelegateType == ''
					|| this.$store.state.buyDelegateType == '1')
					&& !parseFloat(this.delegatePrice)) {
					this.showErr('请输入正确的委托价格!')
					return
				}

				if (!parseFloat(this.buyAmount)
					|| !!(parseFloat(this.buyAmount) % 100)) {
					this.showErr('买入数量必须为100的倍数')
					return
				}

				RemoteDAO.callJCL11116({
					clientId: LocalDAO.getUserCode(),
					stockCode: this.buyStockCode,
					tradeType: this.$store.state.buyDelegateType || '1',
					tradePrice: this.$store.state.buyDelegateType == '' || this.$store.state.buyDelegateType == '1'
						? this.delegatePrice : '0',
					tradeCount: this.buyAmount,
					gameId,
					groupId ,
					marketCd , // 上海
					bfollow: '0',
					followClient: '' // 被跟单客户号
				}, resp => {
					if (resp.error == '0') {
						const { body = {} } = resp.data
						if (body.status == '0') {
							if (body.entrust_no == 0) {
								this.$store.dispatch('setTip', { text: body.describe || '委托失败!' })
								return
							}
							this.$router.push({ path: '/after-trade/delegate-finish', query: {
								tradetype: 'buy',
								code: this.buyStockCode,
								price: this.delegatePrice,
								count: this.buyAmount,
								entrust_no: body.entrust_no,
								gameId
							}})
						} else {
							this.$store.dispatch('setTip', { text: body.describe || '委托失败!' })
						}
					} else {
						this.$store.dispatch('setTip', { text: resp.data })
					}
				})
			}
		}
	}
</script>

<style lang="less" module>
	input {
		padding: 0;
		border-radius: 0;
	}

	.panel, .game-panel {
		padding: 20px 15px 13px 15px;
		background-repeat: no-repeat;
		background-position: 100% -25px;
	    &::-webkit-scrollbar {
		    display: none;
		}
	}

	.panel {
		background-color: #EC4F4F;
	}
	.game-panel {
		background-color: #F7743A;
	}
	.bg_position{
		position:relative;
		z-index:1;
	}
	.trade_mark_bg{
		position:fixed;
		top:19px;
		right:0;
	}
	.max {
		color: #fff;
		margin-top: 16px;
		font-size: 14px;
		line-height: 15px;
	}

	.maxnum {
		display: inline-block;
		margin-left: 36px;
	}


	.buttons {
		position: fixed;
		z-index: 19;
		bottom: 0;
		width: 100%;
		display: -webkit-box;
	}

	.real, .buy {
		-webkit-box-flex: 1;
		height:61px;
    line-height: 61px;
		font-size: 17px;
		text-align: center;
		display: block;
		width: 50%;
		color: #fff;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
	}

	.real {
		background-color: #5D5D5D;
	}

	.buy {
		background-color: #FF5760;
		margin-left: 1px;

		i {
			color: #F3F090;
      font-size: 18px;
		}
	}

	.buyin {
		padding-bottom: 50px;
		&::-webkit-scrollbar {
		    display: none;
		}
	}


</style>
